﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ExpressionTreeLib.ViewModels
{
    [ExpressionType(typeof(BinaryExpression))]
    class BinaryViewModel : NodeViewModel
    {
        private ExpressionType _binaryType;

        protected override Expression CreateExpression()
        {
            var exp = Expression.MakeBinary(this.BinaryType, this.Children[0].Expression,
                                  this.Children[1].Expression);

            if( exp.Method != null)
                this.MethodName = new Method() {MethodInfo = exp.Method};

            return exp;
        }

        public override void LoadExpressionNode(Expression expression)
        {
            base.LoadExpressionNode(expression);
            var binaryExpression = expression as BinaryExpression;
            this._binaryType = expression.NodeType;
            this.MethodName = new Method() {MethodInfo = binaryExpression.Method};

            ExpressionNodeTypeMapping.Create(binaryExpression.Left, this);
            ExpressionNodeTypeMapping.Create(binaryExpression.Right, this);
        }

        public ExpressionType BinaryType
        {
            get {
                return _binaryType;
            }
            set {
                _binaryType = value;
                NotifyOfPropertyChange(()=>BinaryType);
            }
        }

        public Method MethodName { get; private set; }

        protected override void SetAsNew()
        {
            base.SetAsNew();
            this.Children.Add(new EmptyViewModel() { Parent = this });
            this.Children.Add(new EmptyViewModel() { Parent = this });
            this._binaryType = ExpressionType.Equal;
        }
    }
}
